﻿using Azure.Core;
using DataModels.Dto;
using DataModels.Dto.Community;
using DataModels.Entities.AuthCore;
using DataModels.Entities.Base;
using DataModels.Entities.Community;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Linq.Expressions;
using Utils;
using static DataModels.Enums.AuthCore.UserEnum;
using static DataModels.Enums.GeneralEnum;

namespace Services.Community
{
    public class CommunityActivitiesService(SqlSugarClient db) : BaseService(db)
    {
        /// <summary>
        /// 获取社区活动
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public ResponseModel GetCommunityActivities(bool? Active, Guid? ProjectId, DateTime? StartTime, DateTime? EndTime, List<Guid>? CommunityActivitiesUUIDs = null)
        {
            try
            {
                var res = db.Queryable<CommunityActivities, CommunityActivityParticipant>((ca, cap) => new object[]
                {
                    JoinType.Left, ca.UUID == cap.CommunityActivitiesUUID
                })
                //活动是开启的
                .Where(ca => ca.Status == DataModels.Enums.GeneralEnum.Status.Enable && ca.IsDelete == Status.Disable)
                .WhereIF(ProjectId.HasValue, ca => ca.ProjectUUID == ProjectId)
                .WhereIF(StartTime.HasValue, ca => ca.StartTime >= StartTime)
                .WhereIF(EndTime.HasValue, ca => ca.EndTime <= EndTime)
                //没结束的活动
                .WhereIF(Active.HasValue && Active == true, ca => ca.EndTime >= DateTime.Now)
                //已结束的活动
                .WhereIF(Active.HasValue && Active == false, ca => ca.EndTime < DateTime.Now)
                .WhereIF(CommunityActivitiesUUIDs != null, ca => CommunityActivitiesUUIDs.Contains(ca.UUID))
                .OrderBy(ca => ca.StartTime, OrderByType.Desc)
                .GroupBy(ca => ca.UUID)
                .Select((ca, cap) => new GetCommunityActivitiesResponse
                {
                    UUID = ca.UUID,
                    Title = ca.Title,
                    Image = ca.Image,
                    StartTime = ca.StartTime,
                    EndTime = ca.EndTime,
                    Address = ca.Address,
                    Longitude = ca.Longitude,
                    Latitude = ca.Latitude,
                    ContactPerson = ca.ContactPerson,
                    ContactPhone = ca.ContactPhone,
                    NumberOfPeople = SqlFunc.Subqueryable<CommunityActivityPartInfo>()
                    .Where(n => n.IsDeleted != Status.Enable)
                    .Where(a => a.CommunityActivityUUID == ca.UUID)
                    .Count()
                })
                .ToList();
                return Success(res);
            }
            catch (Exception ex)
            {
                return Error($"获取社区活动失败 {ex.Message}");
            }
        }

        /// <summary>
        /// 登录人参加的的社区活动
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public ResponseModel GetCommunityActivitiesParticipateIn(Guid? ProjectId, DateTime? StartTime, DateTime? EndTime)
        {

            List<Guid> CommunityActivitiesUUIDs = db.Queryable<CommunityActivityParticipant>()
                // 是登录人
                .Where(cap => cap.CreateUserUUID == UserUUID)
                .GroupBy(cap => cap.CommunityActivitiesUUID)
                .Select(cap => cap.CommunityActivitiesUUID).ToList();

            return GetCommunityActivities(null, ProjectId, StartTime, EndTime, CommunityActivitiesUUIDs);
        }

        /// <summary>
        /// 获取社区活动详情
        /// </summary>
        /// <param name="CommunityActivitiesId"></param>
        /// <returns></returns>
        public ResponseModel GetCommunityActivitiesDetails(Guid CommunityActivitiesId)
        {
            try
            {
                var res = db.Queryable<CommunityActivities>()
                    // 活动是开启的
                    .Where(ca => ca.Status == DataModels.Enums.GeneralEnum.Status.Enable)
                    .Where(ca => ca.UUID == CommunityActivitiesId)
                    .Select(ca => new
                    {
                        ca.UUID,
                        ca.Title,
                        ca.Content,
                        ca.Image,
                        ca.StartTime,
                        ca.EndTime,
                        ca.Address,
                        ca.Longitude,
                        ca.Latitude,
                        ca.ContactPerson,
                        ca.ContactPhone,
                        ca.Problem,
                        IsJoin = SqlFunc.Subqueryable<CommunityActivityParticipant>()
                            .Where(cap => cap.CommunityActivitiesUUID == ca.UUID)
                            .Where(cap => cap.CreateUserUUID == UserUUID)
                            .Any() ? Status.Enable :  Status.Disable,
                        IsMaxPeople= (ca.MaxJoiners <= SqlFunc.Subqueryable<CommunityActivityPartInfo>()
                                .Where(n => n.IsDeleted != Status.Enable)
                                .Where(a => a.CommunityActivityUUID == ca.UUID)
                                .Count()) ? Status.Enable : Status.Disable,
                        NumberOfPeople = SqlFunc.Subqueryable<CommunityActivityPartInfo>()
                                .Where(n => n.IsDeleted != Status.Enable)
                                .Where(a => a.CommunityActivityUUID == ca.UUID)
                                .Count(),
                        NumberOfComment = SqlFunc.Subqueryable<CommunityActivityComment>()
                            .Where(cac => cac.CommunityActivitiesUUID == ca.UUID
                                      && cac.Status == DataModels.Enums.GeneralEnum.Status.Enable)
                            .Count()
                    })
                    .First();

                return Success(res);
            }
            catch (Exception ex)
            {
                return Error($"获取社区活动详情失败 {ex.Message}");
            }
        }

        /// <summary>
        /// 获取社区活动详情 根据编号
        /// </summary>
        /// <param name="CommunityActivitiesId"></param>
        /// <returns></returns>
        public ResponseModel GetCommunityActivitiesDetails(int ActivitiesNumber)
        {
            try
            {
                var res = db.Queryable<CommunityActivities>()
                    // 活动是开启的
                    .Where(ca => ca.Status == DataModels.Enums.GeneralEnum.Status.Enable)
                    .Where(ca => ca.ActivitiesNumber == ActivitiesNumber)
                    .Select(ca => new
                    {
                        ca.UUID,
                        ca.Title,
                        ca.Content,
                        ca.Image,
                        ca.StartTime,
                        ca.EndTime,
                        ca.Address,
                        ca.Longitude,
                        ca.Latitude,
                        ca.ContactPerson,
                        ca.ContactPhone,
                        ca.Problem,
                        IsJoin = SqlFunc.Subqueryable<CommunityActivityParticipant>()
                            .Where(cap => cap.CommunityActivitiesUUID == ca.UUID)
                            .Where(cap => cap.CreateUserUUID == UserUUID)
                            .Any() ? Status.Enable : Status.Disable,
                        IsMaxPeople = (ca.MaxJoiners <= SqlFunc.Subqueryable<CommunityActivityPartInfo>()
                                .Where(n => n.IsDeleted != Status.Enable)
                                .Where(a => a.CommunityActivityUUID == ca.UUID)
                                .Count()) ? Status.Enable : Status.Disable,
                        NumberOfPeople = SqlFunc.Subqueryable<CommunityActivityPartInfo>()
                                .Where(n => n.IsDeleted != Status.Enable)
                                .Where(a => a.CommunityActivityUUID == ca.UUID)
                                .Count(),
                        NumberOfComment = SqlFunc.Subqueryable<CommunityActivityComment>()
                            .Where(cac => cac.CommunityActivitiesUUID == ca.UUID
                                      && cac.Status == DataModels.Enums.GeneralEnum.Status.Enable)
                            .Count()
                                                    
                    })
                    .First();

                return Success(res);
            }
            catch (Exception ex)
            {
                return Error($"获取社区活动详情失败 {ex.Message}");
            }
        }

        /// <summary>
        /// 获取社区活动评论
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel GetCommunityActivityComment(GetCommunityActivitiesDetailsInfo info)
        {
            if (info == null)
                return Error("缺失参数");

            int total = 0;

            try
            {
                // 预查询评论列表
                var comments = db.Queryable<CommunityActivities, CommunityActivityComment, User>((ca, cac, u) => new object[]
                {
                JoinType.Inner, ca.UUID == cac.CommunityActivitiesUUID,
                JoinType.Left, cac.UserUUID == u.UUID
                })
                .Where(ca => ca.Status == DataModels.Enums.GeneralEnum.Status.Enable)
                .Where((ca, cac) => cac.Status == DataModels.Enums.GeneralEnum.Status.Enable)
                .Where(ca => ca.UUID == info.CommunityActivitiesId)
                //查顶级评论
                .Where((ca, cac) => cac.ParentCommentUUID == null)
                .OrderBy((ca, cac) => cac.CreateTime, OrderByType.Desc)
                .Select((ca, cac, u) => new GetCommunityActivityCommentDto
                {
                    CommunityActivityCommentUUID = cac.UUID,
                    ParentCommentUUID = cac.ParentCommentUUID,
                    AvatarUrl = u.AvatarUrl,
                    UserName = cac.UserName,
                    CreateTime = cac.CreateTime,
                    Content = cac.Content,
                    Children = new List<GetCommunityActivityCommentDto>()
                })
                .ToPageList(info.PageNumber, info.PageSize, ref total);

                // 批量查询所有评论的附件
                var commentIds = comments.Select(c => c.CommunityActivityCommentUUID).ToList();
                var allAttachments = db.Queryable<Attachment>()
                    .Where(at => commentIds.Contains(at.BusinessId))
                    .ToList();

                // 关联附件到评论
                foreach (var comment in comments)
                {
                    comment.Children = GetCommunityActivityCommentChildren(comment.CommunityActivityCommentUUID);
                    comment.Images = GetAttachment(comment.CommunityActivityCommentUUID);
                }
                return PageSuccess(info.PageNumber, info.PageSize, total, comments);
            }
            catch (Exception ex)
            {
                return Error($"获取社区活动评论失败 {ex.Message}");
            }
        }

        private List<GetCommunityActivityCommentDto> GetCommunityActivityCommentChildren(Guid CommunityActivityCommentUUID)
        {
            var comments = db.Queryable<CommunityActivities, CommunityActivityComment, User>((ca, cac, u) => new object[]
            {
                JoinType.Inner, ca.UUID == cac.CommunityActivitiesUUID,
                JoinType.Left, cac.UserUUID == u.UUID
            })
            .Where(ca => ca.Status == DataModels.Enums.GeneralEnum.Status.Enable)
            .Where((ca, cac) => cac.Status == DataModels.Enums.GeneralEnum.Status.Enable)
            .Where((ca, cac) => cac.ParentCommentUUID == CommunityActivityCommentUUID)
            .OrderBy((ca, cac) => cac.CreateTime, OrderByType.Desc)
            .Select((ca, cac, u) => new GetCommunityActivityCommentDto
            {
                CommunityActivityCommentUUID = cac.UUID,
                ParentCommentUUID = cac.ParentCommentUUID,
                AvatarUrl = u.AvatarUrl,
                UserName = cac.UserName,
                CreateTime = cac.CreateTime,
                Content = cac.Content,
                Children = new List<GetCommunityActivityCommentDto>()
            })
            .ToList();
            // 批量查询所有评论的附件
            foreach (var comment in comments)
            {
                comment.Children = GetCommunityActivityCommentChildren(comment.CommunityActivityCommentUUID);
                comment.Images = GetAttachment(comment.CommunityActivityCommentUUID);
            }
            return comments.Cast<GetCommunityActivityCommentDto>().ToList();
        }

        /// <summary>
        /// 参与活动
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel CreateCommunityActivityParticipant(CreateCommunityActivityParticipantInfo info)
        {
            if (info == null)
                return Error("缺失参数");

            try
            {
                CommunityActivities ca = db.Queryable<CommunityActivities>()
                    .Where(ca => ca.Status == Status.Enable)
                    .Where(ca => ca.UUID == info.CommunityActivitiesUUID)
                    .First();
                if (ca == null)
                    return Error("活动未开启");

                CommunityActivityParticipant ckcap = db.Queryable<CommunityActivityParticipant>()
                    .Where(cap => cap.CreateUserUUID == UserUUID)
                    .Where(cap => cap.CommunityActivitiesUUID == ca.UUID)
                    .First();

                if (ckcap != null)
                    return Error("已报名");

                var u = db.Queryable<Customer>().Where(u => u.UUID == UserUUID).First();
                if (u == null)
                    return Error("账号状态异常");

                CommunityActivityParticipant cap = new()
                {
                    CommunityActivitiesUUID = ca.UUID,
                    UserName = u.Name,
                    AvatarUrl = u.PicUrl,
                    CreateUserUUID = UserUUID
                };
                db.Insertable(cap).ExecuteCommand();
                List<CommunityActivityPartInfo> capis = [];
                foreach (var item in info.PersonnelInfo)
                {
                    capis.Add(
                    new()
                    {
                        CommunityActivityUUID = ca.UUID,
                        Problem = ca.Problem,
                        Answer = item,
                        CreateUserUUID = UserUUID
                    });
                }
                db.Insertable(capis).ExecuteCommand();

                return Success();
            }
            catch (Exception ex)
            { 
                return Error($"参与活动失败 {ex.Message}");
            }
        }

        /// <summary>
        /// 获取回答详情
        /// </summary>
        /// <param name="CommunityActivitiesUUID"></param>
        /// <returns></returns>
        public ResponseModel GetAnswerDetail(Guid CommunityActivitiesUUID)
        {
            try
            {
                CommunityActivities ca = db.Queryable<CommunityActivities>()
                    .Where(ca => ca.Status == Status.Enable)
                    .Where(ca => ca.UUID == CommunityActivitiesUUID)
                    .First();

                if (ca == null)
                    return Error("活动未开启");

                List<CommunityActivityPartInfo> res = db.Queryable<CommunityActivityPartInfo>()
                    .Where(capi => capi.IsDeleted == Status.Disable)
                    .Where(capi => capi.CommunityActivityUUID == ca.UUID)
                    .Where(capi => capi.CreateUserUUID == UserUUID)
                    .ToList();
                return Success(res);
            }
            catch (Exception ex)
            {
                return Error($"获取回答详情失败 {ex.Message}");
            }
        }

        /// <summary>
        /// 获取参与人列表
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel GetCommunityActivityParticipant(GetCommunityActivitiesDetailsInfo info)
        {
            if (info == null)
                return Error("缺失参数");

            int total = 0;

            try
            {
                var res = db.Queryable<CommunityActivityPartInfo, Customer>((cp, c) => new object[]
                {
                    JoinType.Left, cp.CreateUserUUID == c.UUID
                })
                .Where((cp, c) =>cp.CommunityActivityUUID==info.CommunityActivitiesId)
                .Where((cp, c) => cp.IsDeleted == 0)
                .Select((cp, c) => new
                {
                    c.PicUrl,
                    cp.Answer,
                    cp.CreateTime
                })
                .ToPageList(info.PageNumber, info.PageSize, ref total);
                return PageSuccess(info.PageNumber, info.PageSize, total, res);
            }
            catch (Exception ex)
            {
                return Error($"获取参与人列表失败 {ex.Message}");
            }
        }

        /// <summary>
        /// 评论活动
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel CreateCommunityActivityComment(CreateCommunityActivityCommentInfo info)
        {
            try
            {
                db.BeginTran();
                // 检查活动是否存在且启用
                var activity = db.Queryable<CommunityActivities>()
                    .Where(ca => ca.UUID == info.CommunityActivitiesId
                                 && ca.Status == DataModels.Enums.GeneralEnum.Status.Enable)
                    .First();
                if (activity == null)
                    return Error("活动不存在");

                if (info.ParentCommentUUID.HasValue)
                {
                    var activitypcac = db.Queryable<CommunityActivityComment>().Where(cac => cac.UUID == info.ParentCommentUUID && cac.Status == DataModels.Enums.GeneralEnum.Status.Enable).First();
                    if (activitypcac == null)
                        return Error("父级评论不存在");
                }

                CommunityActivityComment model = new()
                {
                    UserUUID = UserUUID,
                    UserName = UserName,
                    CommunityActivitiesUUID = info.CommunityActivitiesId,
                    Content = info.Comment,
                    ParentCommentUUID = info.ParentCommentUUID
                };
                CommunityActivityComment cac = db.Insertable(model).ExecuteReturnEntity();
                info.Urls.Select(url => new Attachment
                {
                    BusinessId = cac.UUID,
                    Url = url,
                    CreatedBy = UserUUID,
                }).ToList().ForEach(at =>
                {
                    db.Insertable(at).ExecuteCommand();
                });
                db.CommitTran();
                return Success();
            }
            catch (Exception)
            {
                db.RollbackTran();
                return Error("评论失败，请稍后再试。");
            }
        }

        /// <summary>
        /// 根据小区、楼栋、单元获取客服联系方式 add by tianjh 20250801
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResponseModel GetContactProperty(ContactPropertyInfo info)
        {
            if (info == null)
                return Error("缺失参数");

            try
            {
                var entity = db.Queryable<ContactProperty, Projects,  User>((cp, p, u) => new object[]
                {
                    JoinType.Left, cp.ProjectUUID == p.UUID.ToString(),
                    JoinType.Left, cp.CustomerUUID == u.UUID.ToString()
                })
                .Where( (cp, p, u) => cp.ProjectUUID == info.ProjectUUID)
                .Where((cp, p, u) => u.BuildIdS.Contains(info.BuildingUUID))
                .OrderByDescending((cp, p, u) => cp.CreateTime).First();


                if (entity == null)
                    Success(null); //前端要求返回null 不要返回500状态码。

                return Success(entity);
            }
            catch (Exception ex)
            {
                return Error($"获取物业联系方式失败 {ex.Message}");
            }
        }

        /// <summary>
        /// 根据小区、楼栋、单元获取获取管家信息  add by tianjh 20250802
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public ResponseModel GetButler(CustomerInfo info)
        {
            if (info == null)
                return Error("缺失参数");

            try
            {
                var list = db.Queryable<ContactProperty, Customer>((cp, c) => new object[]
                {
                    JoinType.Left, cp.CustomerUUID == c.UUID.ToString()
                })
                .Where((cp, c) => !string.IsNullOrEmpty(c.WorkTel))
                .WhereIF(!string.IsNullOrEmpty(info.ProjectUUID), cp => cp.ProjectUUID == info.ProjectUUID)
                .WhereIF(!string.IsNullOrEmpty(info.BuildingUUID), cp => cp.BuildingUUID == info.BuildingUUID)
                .WhereIF(!string.IsNullOrEmpty(info.UnitUUID), cp => cp.UnitUUID == info.UnitUUID)
                .OrderByDescending(cp => cp.CreateTime)
                .Select((cp, c) => new
                {
                    ContactPropertyUUID = cp.UUID,              
                    cp.ProjectUUID,
                    cp.BuildingUUID,
                    cp.UnitUUID,
                    cp.ServicePhone,
                    cp.MonitoringRoomPhone,
                    cp.WechatQRCode,
                    cp.Status,
                    cp.Type,
                    cp.StageName,
                    CustomerUUID = c.UUID,
                    c.WorkTel,
                    c.Tel1,
                    c.Tel2,
                    c.Birthday,
                    c.Email,
                    c.Name,
                    c.CustStatus,
                    c.Sex,
                    c.Address
                })
                .First();
                return Success(list);
            }
            catch (Exception ex)
            {
                return Error($"获取客户列表分页数据失败 {ex.Message}");
            }
        }



    }
}
